import { useState } from "react";
import { Button, Popconfirm, Table } from "antd";
import EditDialog from "./EditDialog";
import AddIcon from "@/assets/images/add.png?jsx";
import EditIcon from "@/assets/images/edit.png?jsx";
import CopyIcon from "@/assets/images/copy.png?jsx";
import TrashIcon from "@/assets/images/trash.png?jsx";
import useFetch from "@/lib/hooks/useFetch";
import { deleteDevice, getDeviceList } from "@/lib/api/device";
import { useAtomValue } from "jotai";
import { tokenAtom } from "@/store/user";
import { API_URL } from "@/lib/constants";
import type { IDevice } from "@/lib/types";
import { useMessage } from "@/providers/AntdMessageProvider";
import { getRegionList } from "@/lib/api/region";
import { getMakerList } from "@/lib/api/maker";
import { toggleDeviceRunningStatus } from "@/lib/api/deviceStatus";
import { useModal } from "@/providers/AntdModalProvider";

export default function List() {
  const [edit, setEdit] = useState<{
    visible: boolean;
    type?: "create" | "edit" | "copy";
    record?: IDevice;
  }>({
    visible: false,
    type: undefined,
    record: undefined,
  });
  const token = useAtomValue(tokenAtom);
  const [pagination, setPagination] = useState({
    index: 1,
    size: 10,
    total: 0,
  });

  const modal = useModal();

  const {
    isPending,
    isLoading,
    data,
    refetch: reload,
  } = useFetch({
    fetchFn: (payload) =>
      getDeviceList(payload, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        setPagination((p) => ({ ...p, total: res.total }));
        return res.rows;
      }),
    initialPayload: { pageNum: pagination.index, pageSize: pagination.size },
    immediate: true,
  });

  const { isLoading: isLoadingMakerList, data: makerList } = useFetch({
    fetchFn: () =>
      getMakerList({}, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.rows;
      }),
    immediate: true,
  });

  const { isLoading: isLoadingRegionList, data: regionList } = useFetch({
    fetchFn: () =>
      getRegionList({}, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.rows;
      }),
    immediate: true,
  });

  const message = useMessage();
  function handleDelete(row: IDevice) {
    deleteDevice(row.deviceId, token)
      .then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        message.success("删除成功");
        reload({ pageNum: pagination.index, pageSize: pagination.size });
      })
      .catch((error) => {
        let _message = "删除失败";
        if ("msg" in error) {
          _message = error.msg;
        } else if ("message" in error) {
          _message = error.message;
        }
        message.error(_message);
      });
  }

  function handleToggleDeviceRunningStatus(device: IDevice) {
    const isRunning = device.status === "1";
    modal.confirm({
      title: `是否${isRunning ? "停" : "启"}用设备`,
      onOk() {
        toggleDeviceRunningStatus(
          {
            deviceId: device.deviceId,
            status: isRunning ? "0" : "1",
          },
          token,
        ).then((res) => {
          if (res.code !== 200) {
            throw res;
          }
          reload({ pageNum: pagination.index, pageSize: pagination.size });
        });
      },
    });
  }

  return (
    <>
      <div className="p-6">
        <div className="mb-6">
          <Button
            className="relative w-24"
            onClick={() => setEdit({ visible: true, type: "create" })}
          >
            <AddIcon className="absolute left-1 w-4" />
            <span className="text-sm">添加</span>
          </Button>
        </div>
        <Table
          loading={isLoading || isPending}
          dataSource={data || []}
          rowKey={(row) => row.deviceId}
          pagination={{
            total: pagination.total,
            showSizeChanger: true,
            onChange(page, pageSize) {
              setPagination((p) => ({ ...p, size: pageSize, index: page }));
              reload({ pageNum: page, pageSize });
            },
          }}
        >
          <Table.Column title="编号" dataIndex="deviceId" />
          <Table.Column title="名称" dataIndex="deviceName" />
          <Table.Column
            title="类型"
            render={(row) =>
              [
                row.isHumidity && "湿度",
                row.isTemperature && "温度",
                row.isPressure && "压力",
              ]
                .filter(Boolean)
                .join("+")
            }
          />
          <Table.Column
            title="厂家"
            render={(row) => (
              <>
                <p>
                  厂家：
                  {makerList?.find((el) => el.makerId === row.makerId)
                    ?.makerName || "未知"}
                </p>
                <p>型号：{row.type}</p>
                <p>编号：{row.number}</p>
              </>
            )}
          />
          <Table.Column
            title="连接信息"
            render={(row) => (
              <>
                <p></p>
                <p>
                  IP: {row.ip}:{row.port}
                </p>
                <p>自动连接：{row.isAutoReconnect ? "是" : "否"}</p>
              </>
            )}
          />
          <Table.Column
            title="性能参数"
            render={(row) => (
              <>
                {row.isTemperature === 1 && (
                  <p>
                    温度：{row.temperatureLow}~{row.temperatureHigh}
                  </p>
                )}
                {row.isHumidity === 1 && (
                  <p>
                    湿度：{row.humidityLow}~{row.humidityHigh}
                  </p>
                )}
                {row.isPressure === 1 && (
                  <p>
                    压力：{row.pressureLow}~{row.pressureHigh}
                  </p>
                )}
              </>
            )}
          />
          <Table.Column
            title="存储"
            dataIndex="store"
            render={(row) => (
              <>
                <p>间隔：{row.storeIntervalTime}</p>
                <p>方式：{row.store ? "全部" : "运行时"}</p>
              </>
            )}
          />
          <Table.Column
            title="报警"
            render={(row) =>
              row.alarms.map((el: any, i: number) => (
                <p key={i}>
                  {el.name}：{el.id}
                </p>
              ))
            }
          />
          <Table.Column
            title="启用"
            render={(row) => (
              <Button
                type="text"
                onClick={() => handleToggleDeviceRunningStatus(row)}
              >
                {row.status === "1" ? "已启用" : "已停用"}
              </Button>
            )}
          />
          <Table.Column
            title="图片"
            render={(row) => (
              <img
                className="max-h-16 max-w-16"
                src={`${API_URL}${row.imagePath}`}
                alt=""
              />
            )}
          />
          <Table.Column
            render={(row) => (
              <div>
                <Button
                  type="text"
                  size="small"
                  onClick={() =>
                    setEdit({ visible: true, type: "edit", record: row })
                  }
                >
                  <EditIcon className="size-5" />
                </Button>
                <Button
                  type="text"
                  size="small"
                  onClick={() =>
                    setEdit({ visible: true, type: "copy", record: row })
                  }
                >
                  <CopyIcon className="size-5" />
                </Button>
                <Popconfirm
                  title="确定删除该条记录吗？"
                  onConfirm={() => handleDelete(row)}
                >
                  <Button type="text" size="small">
                    <TrashIcon className="size-5" />
                  </Button>
                </Popconfirm>
                {/* <Button type="text" size="small">
                  <UpIcon className="size-5" />
                </Button>
                <Button type="text" size="small">
                  <DownIcon className="size-5" />
                </Button> */}
              </div>
            )}
          />
        </Table>
      </div>
      <EditDialog
        type={edit.type}
        visible={edit.visible}
        record={edit.record}
        onVisibleChange={(visible) =>
          setEdit({ ...edit, visible, record: undefined })
        }
        reloadList={() =>
          reload({ pageNum: pagination.index, pageSize: pagination.size })
        }
        makerList={makerList || []}
        regionList={regionList || []}
      />
    </>
  );
}
